<template>
  <div class="product-container">
    <!-- 筛选工具栏 -->
    <a-card class="filter-card" :bordered="false">
      <a-form layout="inline" :model="filterForm">
        <a-form-item label="上架状态">
          <a-select
            v-model="filterForm.shelfStatus"
            placeholder="全部状态"
            allow-clear
            @change="handleFilter"
          >
            <a-option
              v-for="item in shelfStatusOptions"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            />
          </a-select>
        </a-form-item>

        <a-form-item label="审核状态">
          <a-select
            v-model="filterForm.auditStatus"
            placeholder="全部状态"
            allow-clear
            @change="handleFilter"
          >
            <a-option
              v-for="item in auditStatusOptions"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            />
          </a-select>
        </a-form-item>

        <a-form-item>
          <a-input-search
            v-model="filterForm.searchKey"
            placeholder="搜索商品标题"
            allow-clear
            search-button
            @search="handleFilter"
          />
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 商品列表 -->
    <div class="product-list">
      <a-card
        v-for="product in productList"
        :key="product.productId"
        class="product-item"
        hoverable
      >
        <div class="product-image">
          <a-image
            :src="product.coverImage"
            :preview="true"
            width="100%"
            height="180"
            fit="cover"
          />
        </div>

        <div class="product-content">
          <div class="product-header">
            <h3 class="product-title">{{ product.title }}</h3>
            <div class="status-tags">
              <a-tag :color="getShelfStatusColor(product.shelfStatus)">
                {{ getShelfStatusText(product.shelfStatus) }}
              </a-tag>
              <a-tag :color="getAuditStatusColor(product.auditStatus)">
                {{ getAuditStatusText(product.auditStatus) }}
              </a-tag>
            </div>
          </div>

          <p class="product-description">{{ product.description }}</p>

          <div class="product-meta">
            <div class="meta-item">
              <span class="meta-label">价格：</span>
              <span class="meta-value">¥{{ product.price }}</span>
            </div>
            <div class="meta-item">
              <span class="meta-label">库存：</span>
              <span class="meta-value">{{ product.stock }}</span>
            </div>
            <div class="meta-item">
              <span class="meta-label">浏览量：</span>
              <span class="meta-value">{{ product.viewCount }}</span>
            </div>
          </div>

          <div class="product-actions">
            <a-button
              type="outline"
              size="small"
              @click="viewDetail(product.productId)"
            >
              详情
            </a-button>
            <a-button
              v-if="product.shelfStatus === 0"
              type="primary"
              size="small"
              @click="handleEdit(product.productId)"
            >
              上架
            </a-button>
            <a-button
              v-if="product.shelfStatus === 1"
              type="outline"
              status="danger"
              size="small"
              @click="handleOffline(product.productId)"
            >
              下架
            </a-button>
          </div>
        </div>
      </a-card>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <a-pagination
        v-model="pagination.current"
        :total="pagination.total"
        :page-size="pagination.size"
        :page-size-options="[8, 16, 24]"
        show-page-size
        show-total
        @change="handlePagination"
        @page-size-change="handlePageSizeChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from "vue";
import { Message } from "@arco-design/web-vue";
import { ProductControllerService } from "@/generated";
import { useRouter } from "vue-router";
import TypeConverter from "@/utils/TypeConverter";

const router = useRouter();

interface Product {
  productId: string;
  farmerId: string;
  title: string;
  description: string;
  price: number;
  stock: number;
  coverImage: string;
  viewCount: number;
  shelfStatus: number; // 0: 未上架, 1: 已上架
  auditStatus: number; // 0: 未审核, 1: 已审核
}

// 筛选表单
const filterForm = reactive({
  shelfStatus: null,
  auditStatus: null,
  searchKey: "",
});

// 分页参数
const pagination = reactive({
  current: 1,
  size: 8,
  total: 0,
});

const productList = ref<Product[]>([]);
const loading = ref(false);

// 状态选项
const shelfStatusOptions = [
  { value: 0, label: "未上架" },
  { value: 1, label: "已上架" },
];

const auditStatusOptions = [
  { value: 0, label: "未审核" },
  { value: 1, label: "已审核" },
];

// 获取商品列表
const fetchProducts = async () => {
  try {
    console.log("shelfStatus", filterForm.shelfStatus);
    console.log("auditStatus", filterForm.auditStatus);
    const shelfStatus = filterForm.shelfStatus;
    const auditStatus = filterForm.auditStatus;
    loading.value = true;
    const res = await ProductControllerService.getMyProductPage({
      pageNumber: pagination.current,
      pageSize: pagination.size,
      shelfStatus: filterForm.shelfStatus,
      auditStatus: filterForm.auditStatus,
      title: filterForm.searchKey,
    });
    console.log("商品列表", res);
    if (res.code === 0) {
      if (res.data === null) {
        productList.value = [];
      }
      productList.value = res.data.records || [];
      pagination.total = res.data.total;
      console.log("商品列表", productList.value);
    }
  } catch (error) {
    Message.error("获取商品列表失败");
  } finally {
    loading.value = false;
  }
};

// 处理筛选
const handleFilter = () => {
  pagination.current = 1; // 重置分页到第一页
  fetchProducts();
};

// 处理分页
const handlePagination = (page: number) => {
  pagination.current = page;
  fetchProducts();
};

//监控到filterForm.shelfStatus变化的时候就重新获取数据
watch(
  () => [filterForm.shelfStatus, filterForm.auditStatus],
  () => {
    fetchProducts();
  }
);
// 监控到filterForm.auditStatus变化的时候就重新获取数据
watch(
  () => [filterForm.shelfStatus, filterForm.auditStatus],
  () => {
    fetchProducts();
  }
);
// 监控到filterForm.searchKey变化的时候就重新获取数据
watch(
  () => [filterForm.shelfStatus, filterForm.auditStatus],
  () => {
    fetchProducts();
  }
);

const handlePageSizeChange = (size: number) => {
  pagination.size = size;
  pagination.current = 1; // 重置分页到第一页
  fetchProducts();
};

// 上架状态显示
const getShelfStatusColor = (status: number) => {
  switch (status) {
    case 0:
      return "orange";
    case 1:
      return "green";
    default:
      return "gray";
  }
};

const getShelfStatusText = (status: number) => {
  switch (status) {
    case 0:
      return "未上架";
    case 1:
      return "已上架";
    default:
      return "未知状态";
  }
};

// 审核状态显示
const getAuditStatusColor = (status: number) => {
  switch (status) {
    case 0:
      return "red";
    case 1:
      return "arcoblue";
    default:
      return "gray";
  }
};

const getAuditStatusText = (status: number) => {
  switch (status) {
    case 0:
      return "未审核";
    case 1:
      return "已审核";
    default:
      return "未知状态";
  }
};

// 商品操作
const viewDetail = (productId: string) => {
  // 查看详情逻辑
  console.log("查看商品详情:", productId);
  const productIdNum = TypeConverter.toNumber(productId);
  router.push(`/product/productDetails/${productIdNum}`);
};

/**
 * 上架商品
 * @param productId
 */
const handleEdit = async (productId: string) => {
  try {
    const number = TypeConverter.toNumber(productId);
    const res = await ProductControllerService.offlineProduct({
      productId: number,
      shelfStatus: 1,
    });
    if (res.code === 0) {
      Message.success("上架成功");
      await fetchProducts();
    }
  } catch (error) {
    Message.error("上架失败");
  }
};

/**
 * 下架商品
 * @param productId
 */
const handleOffline = async (productId: string) => {
  try {
    const number = TypeConverter.toNumber(productId);
    const res = await ProductControllerService.offlineProduct({
      productId: number,
      shelfStatus: 0,
    });
    if (res.code === 0) {
      Message.success("下架成功");
      await fetchProducts();
    }
  } catch (error) {
    Message.error("下架失败");
  }
};

onMounted(() => {
  fetchProducts();
});
</script>

<style scoped lang="scss">
.product-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;

  .filter-card {
    margin-bottom: 16px;
    background-color: var(--color-bg-2);
    border-radius: 6px;

    :deep(.arco-form-item) {
      margin-bottom: 0;
    }
  }

  .product-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 16px;
  }

  .product-item {
    border-radius: 6px;
    transition: all 0.2s;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    }

    .product-image {
      border-radius: 6px 6px 0 0;
      overflow: hidden;
    }

    .product-content {
      padding: 12px;

      .product-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;

        .product-title {
          margin: 0;
          font-size: 16px;
          color: var(--color-text-1);
          font-weight: 500;
        }

        .status-tags {
          display: flex;
          gap: 4px;
        }
      }

      .product-description {
        margin: 0 0 12px;
        font-size: 13px;
        color: var(--color-text-3);
        line-height: 1.5;
      }

      .product-meta {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 8px;
        margin-bottom: 12px;

        .meta-item {
          display: flex;
          align-items: center;

          .meta-label {
            font-size: 13px;
            color: var(--color-text-3);
          }

          .meta-value {
            font-size: 14px;
            color: var(--color-text-1);
            font-weight: 500;
          }
        }
      }

      .product-actions {
        display: flex;
        gap: 8px;
        justify-content: flex-end;
      }
    }
  }

  .pagination-container {
    margin-top: 16px;
    display: flex;
    justify-content: center;
  }
}

@media (max-width: 768px) {
  .product-container {
    padding: 0 12px;

    .product-list {
      grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
    }
  }
}
</style>
